﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace HSInjector
{
    class Program
    {
        static void Main(string[] args)
        {
            hook.injection();
        }
    }

    public class hook
    {
        static string assemblypath = @"D:\HS_dlls\Assembly-CSharp.old.dll";
        static string injectpath = @"C:\Users\Alex\Documents\Visual Studio 2013\Projects\HSInjectDLL\HSInjectDLL\bin\Debug\HSInjectDLL.dll";
        //static string injectpath = @"D:\HS_dlls\HSInjectDLL.dll";

        public static void injection()
        {
            var typeName = "Hub";
            var methodName = "Start";
            var assembly = AssemblyDefinition.ReadAssembly(assemblypath);
            var injassembly = AssemblyDefinition.ReadAssembly(injectpath);
            var typedefinj = injassembly.MainModule.Types.Single(t => t.Name == "loader");
            var injmethDefinition = typedefinj.Methods.Single(t => t.Name == "init");

            var typeDefinition = assembly.MainModule.Types.Single(t => t.Name == typeName);
            var methDefinition = typeDefinition.Methods.Single(t => t.Name == methodName);
            var setMethodWriter = methDefinition.Body.GetILProcessor();

            var firstExistingInstruction = setMethodWriter.Body.Instructions[0];
            setMethodWriter.InsertBefore(firstExistingInstruction, setMethodWriter.Create(OpCodes.Call, assembly.MainModule.Import(injmethDefinition.Resolve())));
            assembly.Write(@"D:\HS_dlls\Assembly-CSharp.dll");
        }
    }
}